<script setup lang="ts">
import { ref, onUnmounted, watchEffect } from 'vue'

const time = ref('00:00:00')
const date = ref('')
const week = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
const flipIndex = ref(0)
function zeroPadding(num: number, length: number) {
  return String(num).padStart(length, '0')
}

function formatTime(dateObj: Date) {
  return `${zeroPadding(dateObj.getHours(), 2)}:${zeroPadding(
    dateObj.getMinutes(),
    2,
  )}:${zeroPadding(dateObj.getSeconds(), 2)}`
}

function formatDate(dateObj: Date) {
  return `${zeroPadding(dateObj.getFullYear(), 4)}-${zeroPadding(
    dateObj.getMonth() + 1,
    2,
  )}-${zeroPadding(dateObj.getDate(), 2)} ${week[dateObj.getDay()]}`
}

// 用于数字动画，拆分每个字符
const animatedTime = ref<string[]>(time.value.split(''))

function updateTime() {
  const now = new Date()
  time.value = formatTime(now)
  date.value = formatDate(now)

  // 动画用数组
  animatedTime.value = time.value.split('')
}

updateTime()
const timerID = setInterval(updateTime, 1000)

onUnmounted(() => {
  clearInterval(timerID)
})
</script>

<template>
  <div class="text-center select-none font-mono">
    <p class="text-gray-600 dark:text-gray-400 text-lg font-semibold mb-2">{{ date }}</p>
    <div class="flex justify-center space-x-1 text-4xl font-bold">
      <template v-for="(char, idx) in animatedTime" :key="idx">
        <span
          class="flip-digit inline-block w-6 h-14 relative perspective-1000"
          :class="{ 'digit-flip': flipIndex === idx }"
        >
          <span class="digit-front absolute inset-0 flex items-center justify-center">{{
            char
          }}</span>
          <span class="digit-back absolute inset-0 flex items-center justify-center">{{
            char
          }}</span>
        </span>
      </template>
    </div>
  </div>
</template>

<style scoped>
.perspective-1000 {
  perspective: 1000px;
}
.flip-digit {
  transition: transform 0.6s ease-in-out;
  transform-style: preserve-3d;
}
.digit-front,
.digit-back {
  backface-visibility: hidden;
  -webkit-backface-visibility: hidden;
}
.digit-front {
  transform: rotateX(0deg);
}
.digit-back {
  transform: rotateX(180deg);
  position: absolute;
  top: 0;
  left: 0;
}
.digit-flip {
  transform: rotateX(180deg);
}
</style>
